package com.qianji.comment;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Repository;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * @Author 钟丽诗
 * @Date 2021.3.10
 *
 */
@Slf4j
@Repository
public class CryptoComment {

    //应用私钥
    public static String private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC1sHwHBPWAI5DJUsL/jdTkP9bp5piRzjFoH57c5pl52i9+P0fCCuln8wooAvovqRpiMb4L8lLLQyaDxSk/rmW6Z6aP/6yDwOKoUz5+Ccc3Koi0vcBghSSr1qK4nxx8RtAEsSnJ+FhPFP0sgzwS8eqqIi0O5zEZBUopJufZ+Gd72EwlYtsu0jyH7IydtVW2foMz6zqEFdVWJxn79L0FCStJXryzV10rOZRmjuTun6b0d39xg5y3m844bix/gr/pHmSsDKeWJQ2zbtOxacoZo5KPnRhLWzHu7wUyrDSrozlfvGfe0eFIjQFhYVGH86OqQLg4nB7OSKvMFaJXJt/Q9mwzAgMBAAECggEAU+gvPyahIg5KvU8FUvPzT33UCK0/5IYu9wEzYpz0X/vNVyZuQ0S6yhDJrfTCCeS0lIiYVfgRGGHolY4mIIyv2kgn+fR/fVFE26ul/psRb36rJ51CDNEwQFOdTlnc09/4DVKsE+QnFE6DJV1uDum+D9g8qtdGK2Hv/9VB2b4IPH69npg1UMlNotccL5DZMSUX/jq+eudJibe8Gab78BJghyAY0CHoC3NsqMOUtKjsMpHJ/JNIbcARCi1Ix+zgz4e837M2KD6TaqNVQD+98iM3gbL71zsjB2Bjr0xvZVm4KG9AcOldaHUi2sZ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nHNyqItL3AYIUkq9aiuJ8cfEbQBLEpyfhYTxT9LIM8EvHqqiItDucxGQVKKSbn2fhne9hMJWLbLtI8h+yMnbVVtn6DM+s6hBXVVicZ+/S9BQkrSV68s1ddKzmUZo7k7p+m9Hd/cYOct5vOOG4sf4K/6R5krAynliUNs27TsWnKGaOSj50YS1sx7u8FMqw0q6M5X7xn3tHhSI0BYWFRh/OjqkC4OJwezkirzBWiVybf0PZsMwIDAQAB";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data 待加密数据
     * @param publicKey 公钥
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data 待解密数据
     * @param privateKey 私钥
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 签名
     *
     * @param data 待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    public static Object method(String srcData, String signs,String data,String privateKey) {

        Sign sign = SecureUtil.sign(SignAlgorithm.MD5withRSA);
        String strSign = String.valueOf(sign.sign(srcData.getBytes()));

        log.info("签名：{}",strSign);

        if(!signs.equals(strSign)){
            return "验签失败";
        }

        log.info("验签成功");
        //解密
        RSA rsa = new RSA(privateKey,null);
        String str = rsa.decryptStr(data, KeyType.PrivateKey);
        log.info("解密后的内容：{}",str);

        return rsa.encryptBase64(str.getBytes(),KeyType.PrivateKey);

    }

}
